package com.itchen.hospital.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itchen.hospital.exception.CustomException;
import com.itchen.hospital.mapper.UserMapper;
import com.itchen.hospital.mapper.UserMapper;
import com.itchen.hospital.pojo.User;
import com.itchen.hospital.pojo.Params;
import com.itchen.hospital.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 查询所有
     * @return
     */
    @Override
    public List<User> getAll() {
        return userMapper.getAll();
    }

    //条件查询
    @Override
    public PageInfo<User> search(Params params) {
        //处理分页
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<User> list = userMapper.findBySearch(params);
        return PageInfo.of(list);
    }

    //添加
    @Override
    public void add(User user) {
        //先查询数据库数据,如果此账号在数据库中已存在，则不能添加
        if (userMapper.findByAccount(user.getAccount()) != null) {
            throw new CustomException("此账号已存在,无法添加!");
        }
        user.setRole("USER");
        //设置默认密码
        user.setPassword("123456");
        userMapper.add(user);
    }

    //修改
    @Override
    public void update(User user) {
        userMapper.update(user);
    }

    //根据account查询
    @Override
    public User findByAccount(String account) {
        User user = userMapper.findByAccount(account);
        return user;
    }

    //删除
    @Override
    public void delete(String account) {
        userMapper.delete(account);
    }

    //批量删除
    @Override
    public void batchDelete(List<User> users) {
        users.forEach(user -> {
            userMapper.delete(user.getAccount());
        });
    }
}
